<template>
  <div class="container">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd" icon="Plus">新增展示</el-button>
    </div>

    <!-- 数据展示 -->
    <div class="card-list">
      <el-card v-for="item in listData" :key="item.id" class="show-card">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <el-text class="title-text" tag="b" truncated>{{ item.title }}</el-text>
            </div>
            <div class="operate-btns">
              <el-button type="warning" size="small" @click="handleEdit(item.id)">
                <img src="../../assets//icons/edit.svg" alt="icon" style="width: 16px; height: 16px; margin-right: 8px;" />
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(item.id)">
                <img src="../../assets//icons/delete.svg" alt="icon" style="width: 16px; height: 16px; margin-right: 8px;" />
                删除
              </el-button>
            </div>
          </div>
        </template>

        <div class="media-container">
          <el-image :src="item.imgUrl" fit="cover" class="media-preview" :preview-src-list="[item.imgUrl]" />
          <video v-if="item.videoUrl" controls class="media-preview">
            <source :src="item.videoUrl" type="video/mp4">
          </video>
        </div>

        <div class="content-box">
          <el-text truncated>{{ item.content }}</el-text>
          <div class="time-info">
            <el-text type="info" size="small">创建：{{ formatTime(item.createdAt) }}</el-text>
            <el-text type="info" size="small">更新：{{ formatTime(item.updatedAt) }}</el-text>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑展示' : '新增展示'">
      <el-form :model="formData" label-width="80px" :rules="formRules">
        <el-form-item label="标题:" prop="title">
          <el-input 
            v-model="formData.title" 
            placeholder="请输入展示标题"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="图片:" prop="imgUrl">
          <el-upload
            action="/api/admin/common/upload"
            list-type="picture-card"
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :on-preview="handlePictureCardPreview"
            :file-list="formData.imgUrl ? [{ url: formData.imgUrl }] : []"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogImageVisible">
            <img :src="imgUrl" alt="预览图片" style="width: 100%" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="视频:" prop="videoUrl">
          <el-upload
            action="/api/admin/common/upload"
            :limit="1"
            :on-exceed="handleVideoExceed"
            :on-success="handleVideoSuccess"
            :on-remove="handleVideoRemove"
            :accept="videoMimeTypes"
            :file-list="videoFileList"
          >
            <el-button type="primary">点击上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传 MP4 格式视频，大小不超过 100MB
              </div>
            </template>
          </el-upload>

          <!-- 视频预览 -->
          <div v-if="formData.videoUrl" class="video-preview2">
            <video controls class="preview-player">
              <source :src="formData.videoUrl" type="video/mp4">
              您的浏览器不支持视频播放
            </video>
          </div>
        </el-form-item>
        
        <el-form-item label="展示内容" prop="content">
          <el-input v-model="formData.content" type="textarea" :rows="4" placeholder="请输入展示内容" maxlength="500"
            show-word-limit />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// API配置
const API = {
  getList: '/api/admin/mp/military-train', // 获取数据
  addItem: '/api/admin/mp/military-train', // 新建展示
  updateItem: '/api/admin/mp/military-train', // 更新数据
  deleteItem: '/api/admin/mp/military-train', // 删除数据
  uploadImage: '/api/admin/common/upload' // 图片上传接口
}

// 数据相关
const listData = ref([]) // 列表数据
const dialogVisible = ref(false) // 控制弹窗显示
const isEdit = ref(false) // 是否为编辑模式
const currentId = ref(null) // 当前操作的ID
const videoFileList = ref([])
const videoMimeTypes = 'video/mp4'

// 表单数据
const formData = reactive({
  title: '', // 新增标题字段
  imgUrl: '',
  videoUrl: '',
  content: ''
})

// 图片上传相关
const imgUrl = ref('') // 上传后的图片地址
const dialogImageVisible = ref(false) // 控制图片预览弹窗


// 表单验证规则
const formRules = {
  title: [{ required: true, message: '请填写标题', trigger: 'blur' }], // 标题必填
  imgUrl: [{ message: '请填写图片地址', trigger: 'blur' }],
  content: [{ required: true, message: '请填写展示内容', trigger: 'blur' }]
}

// 生命周期钩子：组件挂载时加载数据
onMounted(() => {
  fetchData()
})

// 方法：获取数据
const fetchData = async () => {
  try {
    const { data } = await axios.get(API.getList)
    listData.value = data.data // 将获取的数据赋值给列表
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

// 方法：处理新增操作
const handleAdd = () => {
  isEdit.value = false // 设置为新增模式
  resetForm() // 重置表单
  dialogVisible.value = true // 打开弹窗
}

// 方法：处理编辑操作
const handleEdit = async (id) => {
  try {
    isEdit.value = true
    currentId.value = id
    
    // 发起请求获取完整数据
    const { data } = await axios.get(`${API.getList}/${id}`)
    const detailData = data.data
    
    // 更新表单数据
    Object.assign(formData, detailData)
    
    // 直接使用表单数据控制图片显示
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

// 方法：处理删除操作
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该展示信息？', '警告', { type: 'warning' }) // 确认弹窗
    await axios.delete(`${API.deleteItem}/${id}`) // 发送删除请求
    ElMessage.success('删除成功') // 提示成功
    fetchData() // 重新加载数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消删除') // 提示失败
    }
  }
}

// 方法：提交表单（新增或编辑）
const submitForm = async () => {
  try {
    const url = isEdit.value ? API.updateItem : API.addItem // 根据模式选择URL
    const method = isEdit.value ? 'put' : 'post' // 根据模式选择请求方法
    
    // 发送请求
    await axios[method](url, {
      ...formData, // 展开表单数据
      id: currentId.value // 添加ID字段
    })
    
    ElMessage.success('操作成功') // 提示成功
    dialogVisible.value = false // 关闭弹窗
    fetchData() // 重新加载数据
  } catch (error) {
    ElMessage.error('操作失败') // 提示失败
  }
}

// 方法：重置表单
const resetForm = () => {
  Object.assign(formData, {
    title: '', // 重置标题
    imgUrl: '',
    videoUrl: '',
    content: ''
  })
  currentId.value = null // 清空当前ID
}

// 方法：格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 方法：处理图片上传成功
const handleUploadSuccess = (response, file) => {
  if (response.code === 1) {
    formData.imgUrl = response.data // 将上传后的图片地址赋值给表单
    imgUrl.value = response.data // 更新图片地址
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 方法：处理超出上传限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传一张图片')
}

// 方法：处理图片移除
const handleRemove = () => {
  formData.imgUrl = '' // 清空图片地址
  imgUrl.value = '' // 清空图片地址
}

// 方法：处理图片预览
const handlePictureCardPreview = () => {
  dialogImageVisible.value = true // 打开图片预览弹窗
}

// 视频上传成功处理
const handleVideoSuccess = (response, file) => {
  if (response.code === 1) {
    formData.videoUrl = response.data
    videoFileList.value = [{
      name: file.name,
      url: response.data
    }]
    ElMessage.success('视频上传成功')
  }
}

// 视频移除处理
const handleVideoRemove = () => {
  formData.videoUrl = ''
  videoFileList.value = []
}

// 视频超出限制处理
const handleVideoExceed = () => {
  ElMessage.warning('最多只能上传一个视频文件')
}
</script>

<style scoped>
/* 外层容器适配 */
.container {
  flex: 1;  /* 继承父级弹性布局 */
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: #f5f7fa;
  min-height: 0;  /* 重要：修复Safari浏览器中的布局问题 */
}

/* 操作栏固定高度 */
.operation-bar {
  margin-bottom: 20px;
  flex-shrink: 0;  /* 禁止收缩 */
}

/* 卡片列表区域 */
.card-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  min-height: calc(100% - 40px); /* 保证最小高度 */
}


/* 卡片高度优化 */
/* 卡片高度优化 */
.show-card {
  height: 570px;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px; /* 增加底部间距 */
}

.show-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(to right, #f8f9fa, #e9ecef);
  border-radius: 4px 4px 0 0;
}
.title-wrapper {
  flex: 1;
  min-width: 0;
  margin-right: 15px;
}

.title-text {
  font-size: 16px;
  color: #1a1a1a;
  letter-spacing: 0.5px;
  display: block;
  line-height: 1.4;
}


.operate-btns {
  flex-shrink: 0;
  display: flex;
  gap: 8px;
}

/* 卡片内容布局优化 */
.media-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin: 0 0 15px;
}
.media-preview {
  width: 280px;
  height: 160px;
  border-radius: 4px;
  object-fit: cover;
}


/* 内容区域自适应 */
.content-box {
  padding: 0 8px;
  margin-top: auto;  /* 将内容推到卡片底部 */
}

.time-info {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
}

/* 弹窗视频预览优化 */
.video-preview2 {
  margin-top: 15px;
  max-width: 600px;
}
.preview-player {
  width: 100%;
  max-width: 500px;
  border-radius: 4px;
  background: #000;
} 

</style>